package com.zhengxin.one.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhengxin.one.common.Result;
import com.zhengxin.one.common.ResultPage;
import com.zhengxin.one.dto.*;
import com.zhengxin.one.entity.*;
import com.zhengxin.one.entity.client.RecordAdd;
import com.zhengxin.one.entity.entityClass.BillAdd;
import com.zhengxin.one.entity.entityClass.Page;
import com.zhengxin.one.mapper.BillMapper;
import com.zhengxin.one.mapper.PolicyAddrMapper;
import com.zhengxin.one.service.PolicyAddrService;
import com.zhengxin.one.service.impl.BillServiceipml;
import com.zhengxin.one.service.impl.RecordServiceImpl;
import com.zhengxin.one.service.impl.UserServiceIpml;
import com.zhengxin.one.utils.HttpUtil;
import com.zhengxin.one.utils.JobUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;


@RestController
@RequestMapping(value = "shangshebao")
public class BillController {

    private final Logger log = LoggerFactory.getLogger(BillController.class);

    //服务费
    public static int SERVICECOST=200;
    //第三方授权码
    public static String AUTHCODE="3db06a35534e7b7920a3415cf13ff038";

    @Autowired
    private RecordServiceImpl recordService;
    @Autowired
    private BillServiceipml billService;
    @Autowired
    private PolicyAddrService policyAddrService;
    //先生成sign
    private static String app="appkey=";
    private static String appkey="2a7f0d5N13Y9deT6";


    public String getCompanyName(String useId) {
            return policyAddrMapper.getNameC(useId);
    }
    //增员基础信息添加
    @RequestMapping(value = "baseInfo",method = RequestMethod.POST)
    public Result insertBase(@RequestBody BillBase bean){
        //检验参保人是否已存在
        String id_card=bean.getId_card();
        if(!billService.check(id_card)){
            //添加参保人信息
            bean.setCommercial_id(0);
            bean.setAccumulation_id(0);
            bean.setSociety_id(0);
            billService.insertAll(bean);
            return Result.success(bean);
        }
            //参保人已存在查询参保情况
        return Result.success(billService.billinfo(id_card));
    }
    //参保信息预览
    @RequestMapping(value = "show",method = RequestMethod.POST)
    public Result getShow(@RequestBody Object bean){
        return Result.success(bean);
    }
    //增员社保，公积金，商保参保信息
    @RequestMapping(value = "billInfo",method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result insertBills(@RequestBody BillAdd bean) throws NoSuchAlgorithmException {
        System.out.println(111);
        BillBase Tmap = new BillBase();
        if(!billService.check(bean.getId_card())){
            //参保人不存在（先添加基本信息）
            Tmap.setCompany_id(bean.getCompany_id());
            Tmap.setNationality(bean.getNationality());
            Tmap.setName(bean.getName());
            Tmap.setId_card(bean.getId_card());
            Tmap.setRegion(bean.getRegion());
            Tmap.setResidence_type(bean.getResidence_type());
            Tmap.setBirthday(bean.getBirthday());
            Tmap.setSex(bean.getSex());
            Tmap.setPhone(bean.getPhone());
            Tmap.setNation(bean.getNation());
            Tmap.setSociety_id(0);
            Tmap.setAccumulation_id(0);
            Tmap.setCommercial_id(0);
            if(billService.insertAll(Tmap)!=1){
                return Result.fail("添加失败");
            }
        }
        //参保人存在或已经新加 则添加社保公积金商保
        //社保添加
        if (bean.getSolist() != null && !bean.getSolist().isEmpty()) {
            List<BillSociety> list = bean.getSolist();
            for (BillSociety x:list) {
                x.setId_card(bean.getId_card());
                x.setStatus(1);
                x.setHandle_type(1);
                x.setPay_status(1);
                billService.insertAllSociety(x);
                int bill_id = x.getId();
                //修改基础信息与之对应
                int info = billService.handbases(bean.getId_card(),1,bill_id);
                if(info!=1){
                    return Result.fail("添加失败");
                }
                //添加历史记录
                RecordAdd recordAdd = new RecordAdd();
                recordAdd.setId_card(bean.getId_card());
                recordAdd.setCompany_id(bean.getCompany_id());
                recordAdd.setName(bean.getName());
                recordAdd.setNationality(bean.getNationality());
                recordAdd.setSex(bean.getSex());
                recordAdd.setResidence_type(bean.getResidence_type());
                recordAdd.setService_type(1);
                recordAdd.setHandle_type(1);
                recordAdd.setStatus(1);
                recordAdd.setS_region(x.getRegion());
                recordAdd.setS_cbase(x.getCbase());
                recordAdd.setS_jointime(x.getJointime());
                recordAdd.setTtype(1);
                if(recordService.setPerson(recordAdd)!=1){
                    return Result.fail("记录添加失败");
                }
            }
        }
        System.out.println(222);
        //公积金添加
        if (bean.getAclist() != null && !bean.getAclist().isEmpty()) {
            List<BillAccumulation> list = bean.getAclist();
            for (BillAccumulation x:list) {
                x.setId_card(bean.getId_card());
                x.setStatus(1);
                x.setHandle_type(1);
                x.setPay_status(1);
                billService.insertAllAccumulation(x);
                int bill_id = x.getId();
                //修改基础信息与之对应
                int info = billService.handbases(bean.getId_card(),2,bill_id);
                if(info!=1){
                    return Result.fail("添加失败");
                }
                //添加历史记录
                RecordAdd recordAdd = new RecordAdd();
                recordAdd.setId_card(bean.getId_card());
                recordAdd.setCompany_id(bean.getCompany_id());
                recordAdd.setName(bean.getName());
                recordAdd.setNationality(bean.getNationality());
                recordAdd.setSex(bean.getSex());
                recordAdd.setResidence_type(bean.getResidence_type());
                recordAdd.setService_type(1);
                recordAdd.setHandle_type(1);
                recordAdd.setStatus(1);
                recordAdd.setA_region(x.getRegion());
                recordAdd.setA_cbase(x.getCbase());
                recordAdd.setA_e_company_ratio(x.getCompany_ratio());
                recordAdd.setA_e_person_ratio(x.getPerson_ratio());
                recordAdd.setA_jointime(x.getJointime());
                recordAdd.setTtype(2);
                if(recordService.setPerson(recordAdd)!=1){
                    return Result.fail("记录添加失败");
                }
            }
        }
        System.out.println(3333);
        //商保添加
        if (bean.getColist() != null && !bean.getColist().isEmpty()) {
            List<BillCommercial> list = bean.getColist();
            for (BillCommercial x:list) {
                x.setId_card(bean.getId_card());
                x.setStatus(1);
                x.setHandle_type(1);
                x.setPay_status(1);
                billService.insertAllCommercia(x);
                int bill_id = x.getId();
                //修改基础信息与之对应
                int info = billService.handbases(bean.getId_card(),3,bill_id);
                if(info!=1){
                    return Result.fail("添加失败");
                }
                //添加历史记录
                RecordAdd recordAdd = new RecordAdd();
                recordAdd.setId_card(bean.getId_card());
                recordAdd.setCompany_id(bean.getCompany_id());
                recordAdd.setName(bean.getName());
                recordAdd.setNationality(bean.getNationality());
                recordAdd.setSex(bean.getSex());
                recordAdd.setResidence_type(bean.getResidence_type());
                recordAdd.setService_type(1);
                recordAdd.setHandle_type(1);
                recordAdd.setStatus(1);
                recordAdd.setC_plan(x.getPlan());
                recordAdd.setTtype(3);
                if(recordService.setPerson(recordAdd)!=1){
                    return Result.fail("记录添加失败");
                }
            }
        }
        System.out.println(4444);
        //创建订单
        //获取token

        String token = getToken();
        //订单最外层
        CreateOrderDTO createOrderDTO = new CreateOrderDTO();
        createOrderDTO.setUserid(Integer.parseInt(bean.getCompany_id()));
        createOrderDTO.setOrder_type(3);
        createOrderDTO.setDeduction_amount(0);
        createOrderDTO.setAddress("");
        createOrderDTO.setShipping_fee(SERVICECOST*100);
        //计算社保总额
        Double soTatal=0.00;
        Double acTatal=0.00;
        Double coTatal=0.00;
        String Stime=null;
        String Atime=null;
        String Ctime=null;
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
        if(!bean.getSolist().isEmpty()){
            List<BillSociety> solist = bean.getSolist();
            for (BillSociety x:solist) {
                String planId = policyAddrMapper.getPlanId(x.getPlan(),1);
                //获取险种
                List<Map<String, BigDecimal>> rish = policyAddrMapper.getRish(planId, 1);
                for (Map<String,BigDecimal> y:rish) {

                    soTatal= Double.parseDouble(y.get("comp_ratio").toString())*Double.parseDouble(x.getCbase())+Double.parseDouble(y.get("emp_ratio").toString())*Double.parseDouble(x.getCbase());
                }
                Stime=sdf2.format(x.getJointime());
            }
        }
        //计算公积金总额
        if(!bean.getAclist().isEmpty()){
            List<BillAccumulation> aclist = bean.getAclist();
            for (BillAccumulation x:aclist) {
                String planId = policyAddrMapper.getPlanId(x.getPlan(),2);
                //获取险种
                List<Map<String, BigDecimal>> rish = policyAddrMapper.getRish(planId, 2);
                for (Map<String,BigDecimal> y:rish) {
                    acTatal=  Double.parseDouble(y.get("comp_ratio").toString())*Integer.parseInt(x.getCbase())+Double.parseDouble(y.get("emp_ratio").toString())*Integer.parseInt(x.getCbase());
                }
                Atime=sdf2.format(x.getJointime());
            }
        }
        //计算商保总额
        if(!bean.getColist().isEmpty()){
            List<BillCommercial> colist = bean.getColist();
            for (BillCommercial x:colist) {
                coTatal=Double.parseDouble(policyAddrMapper.getComminsures(x.getPlan()));
                Ctime=sdf2.format(x.getJointime());
            }
        }
        Double Tatal=soTatal+acTatal+coTatal;
        System.out.println(Tatal);
        createOrderDTO.setAmount((int) (Tatal*100));
        createOrderDTO.setPayment_amount((int) (soTatal*100));
        createOrderDTO.setMemo("");
        createOrderDTO.setAuth_code(AUTHCODE);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        long time = timestamp.getTime();
        createOrderDTO.setSign_time(BigInteger.valueOf(time));

        //订单中层
        OrderMiddDTO orderMiddDTO = new OrderMiddDTO();
        orderMiddDTO.setApplication_number(6);
        orderMiddDTO.setSubtitle("商社保");
        orderMiddDTO.setQuantity(1);
        orderMiddDTO.setPrice((int) (Tatal*100));
        orderMiddDTO.setService_price(SERVICECOST*100);
        orderMiddDTO.setPerson_number(1);
        orderMiddDTO.setOrder_item_type(3);
        orderMiddDTO.setMemo("");
        //订单最内层
        OrderMiddInfoDTO orderMiddInfoDTO = new OrderMiddInfoDTO();
        orderMiddInfoDTO.setName(bean.getName());
        orderMiddInfoDTO.setIdentity_number(bean.getId_card());
        orderMiddInfoDTO.setPhone(bean.getPhone());
        orderMiddInfoDTO.setAmount((int) (Tatal*100));
        orderMiddInfoDTO.setInsurance_for_year_month(Stime);
        orderMiddInfoDTO.setInsurance_amount((int) (soTatal*100));
        orderMiddInfoDTO.setReservefunds_for_year_month(Atime);
        orderMiddInfoDTO.setReservefunds_amount((int) (acTatal*100));
        orderMiddInfoDTO.setBusiness_for_year_month(Ctime);
        orderMiddInfoDTO.setBusiness_amount((int) (coTatal*100));
        orderMiddInfoDTO.setDisability_amount(0);
        ArrayList<OrderMiddInfoDTO> orderMiddInfoDTOArrayList = new ArrayList<>();
        orderMiddInfoDTOArrayList.add(orderMiddInfoDTO);
        orderMiddDTO.setOrder_item_detail(orderMiddInfoDTOArrayList);
        ArrayList<OrderMiddDTO> orderMiddDTOArrayList = new ArrayList<>();
        orderMiddDTOArrayList.add(orderMiddDTO);
        createOrderDTO.setOrder_item(JSON.toJSONString(orderMiddDTOArrayList));
        String sign = getSign(createOrderDTO);
        createOrderDTO.setSign(sign);
        String s1 = JSON.toJSONString(createOrderDTO);
        System.out.println(s1);
        String orderID=null;
        try {
            String info = HttpUtil.sendPost("https://openapi.renshihr.cn/v1/order/add",s1,token);
            System.out.println(info);
            OrderBackDTO jsonObject = JSON.parseObject(info,OrderBackDTO.class);
            if(!"E00000".equals(jsonObject.getStatus_code())){
                return Result.fail("创建人事云订单失败");
            }
            orderID = jsonObject.getResult_data().get("order_info").get("order_number");
            System.out.println(orderID);
        }catch (Exception e)
        {e.getMessage();}
        //生成本地订单
        KeepListDTO keepListDTO = new KeepListDTO();
        keepListDTO.setName(bean.getName());
        keepListDTO.setUserId(bean.getCompany_id());
        keepListDTO.setIdCard(bean.getId_card());
        String type1=null;
        if(!bean.getSolist().isEmpty()){
            type1="1";
            keepListDTO.setDateTime(Stime);
        }
        if(!bean.getAclist().isEmpty()){
            type1=type1+",2";
            keepListDTO.setDateTime(Atime);
        }
        if(!bean.getAclist().isEmpty()){
            type1=type1+",3";
            keepListDTO.setDateTime(Ctime);
        }
        if(!bean.getSolist().isEmpty()){
            Map<String, String> caseName = policyAddrMapper.getCaseName(bean.getId_card(), 1);
            //查询方案下的险种
            List<caseInfoDTO> caseInfos = policyAddrMapper.getCaseInfos(caseName.get("plan"), 1);
            double comPay=0.00;
            double perPay=0.00;
            for ( caseInfoDTO x:caseInfos) {
                for (BillSociety y:bean.getSolist()) {
                    comPay+=x.getCompM()*Integer.parseInt(y.getCbase());
                    perPay+=x.getEmpM()*Integer.parseInt(y.getCbase());
                };
            }
            keepListDTO.setSo_company(comPay);
            keepListDTO.setSo_person(perPay);
        }
        if(!bean.getAclist().isEmpty()){
            double comPay=0.00;
            double perPay=0.00;
                for (BillAccumulation y:bean.getAclist()) {
                    comPay+=Integer.parseInt(y.getCompany_ratio())*Integer.parseInt(y.getCbase());
                    perPay+=Integer.parseInt(y.getPerson_ratio())*Integer.parseInt(y.getCbase());
                };

            keepListDTO.setAc_company(comPay);
            keepListDTO.setAc_person(perPay);
        }
        keepListDTO.setSoPay(soTatal);
        keepListDTO.setCoPay(coTatal);
        keepListDTO.setAcPay(acTatal);
        keepListDTO.setOrderStates(type1);
        keepListDTO.setServiceFee(SERVICECOST);
        keepListDTO.setOrder_info("增员");
        keepListDTO.setTotalPay(Tatal);
        keepListDTO.setUuid(orderID);
        keepListDTO.setName(bean.getName());
        try{
            policyAddrMapper.insertOrder(keepListDTO);
        }catch (Exception e){
            e.getMessage();
        }
        //设置返回值
        KeepBackInfoDTO so = new KeepBackInfoDTO();
        so.setAmount(soTatal);
        so.setFor_year_month(Stime);
        KeepBackInfoDTO ac = new KeepBackInfoDTO();
        ac.setAmount(acTatal);
        ac.setFor_year_month(Atime);
        KeepBackInfoDTO co = new KeepBackInfoDTO();
        co.setAmount(coTatal);
        co.setFor_year_month(Ctime);
        KeepBackDTO keepBackDTO = new KeepBackDTO();
        keepBackDTO.setSo(so);
        keepBackDTO.setAc(ac);
        keepBackDTO.setCo(co);
        keepBackDTO.setName(bean.getName());
        keepBackDTO.setIdCard(bean.getId_card());
        keepBackDTO.setAmount(Tatal);
        keepBackDTO.setServicePay(SERVICECOST*100);
        keepBackDTO.setCanbaojin(0.00);
        String format = "YYYY-MM-dd";
        String formatDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
        keepBackDTO.setOrderText("增员订单"+" "+formatDate+"("+"1"+"人"+")");
        keepBackDTO.setOrderId(orderID);
        return Result.success(keepBackDTO);
    }
    @Autowired
    private BillMapper billMapper;
    //获取续缴列表
    @RequestMapping(value = "keepPay",method = RequestMethod.GET)
    public ResultPage keepPay(@RequestParam String keyword,@RequestParam String companyId, @RequestParam int page, @RequestParam int size){
        PageHelper.startPage(page,size);
        List<BillBase> billBase = billMapper.keepList(companyId,keyword);
        PageInfo pageInfo = new PageInfo(billBase);
        Page pageinfos =new Page();
        pageinfos.setPageNum(pageInfo.getPageNum());
        pageinfos.setTotal((int)pageInfo.getTotal());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
        ArrayList<keepPayDTO> keepPayDTOS = new ArrayList<>();
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.now().plusMonths(1);
        if(billBase.size()>0){
            billBase.forEach(x->{
                keepPayDTO keepPayDTO = new keepPayDTO();
                keepPayDTO.setName(x.getName());
                keepPayDTO.setId_card(x.getId_card());
                BillSociety society = billMapper.keepLists(x.getId_card(),fmt.format(localDate));
                if(!BeanUtil.isEmpty(society)){
                    List<caseInfoDTO> caseInfos = policyAddrMapper.getCaseInfos(society.getPlan(), 1);
                    Integer Cbase = Integer.valueOf(society.getCbase());
                    AtomicReference<Double> info= new AtomicReference<>(0.00);
                    if(caseInfos.size()>0){
                        caseInfos.forEach(term->{
                            Double aDouble = Double.valueOf(decimalFormat.format((float) term.getCompRatio() / 100 * Cbase));
                            Double aDouble1 = Double.valueOf(decimalFormat.format((float) term.getEmpRatio() / 100 * Cbase));
                            info.set(aDouble + aDouble1+info.get());
                        });
                    }
                    society.setKeepTime(dateTimeFormatter.format(LocalDate.now()));
                    society.setTotal(String.valueOf(info));
                    keepPayDTO.setSoInfo(society);
                }
                BillAccumulation billAccumulation = billMapper.keepLista(x.getId_card(),fmt.format(localDate));
                if(!BeanUtil.isEmpty(billAccumulation)){
                    List<caseInfoDTO> caseInfos = policyAddrMapper.getCaseInfos(billAccumulation.getPlan(), 2);
                    Integer Cbase = Integer.valueOf(billAccumulation.getCbase());
                    AtomicReference<Double> info= new AtomicReference<>(0.00);
                    caseInfos.forEach(term->{
                        Double aDouble = Double.valueOf(decimalFormat.format((float) term.getCompRatio() / 100 * Cbase));
                        Double aDouble1 = Double.valueOf(decimalFormat.format((float) term.getEmpRatio() / 100 * Cbase));
                        info.set(aDouble + aDouble1+info.get());
                    });
                    billAccumulation.setKeepTime(dateTimeFormatter.format(LocalDate.now()));
                    billAccumulation.setTotal(String.valueOf(info));
                    keepPayDTO.setAcInfo(billAccumulation);
                }
                BillCommercial billCommercial = billMapper.keepListc(x.getId_card(),fmt.format(localDate));
                if(!BeanUtil.isEmpty(billCommercial)){
                    String comminsures = policyAddrMapper.getComminsures(billCommercial.getPlan());
                    billCommercial.setKeepTime(dateTimeFormatter.format(LocalDate.now()));
                    billCommercial.setTotal(comminsures);
                    keepPayDTO.setCoInfo(billCommercial);
                }
                keepPayDTOS.add(keepPayDTO);
            });
        }
        return ResultPage.successp(keepPayDTOS,pageinfos);
    }

    @Autowired
    private PolicyAddrMapper policyAddrMapper;

    //获取参保地
    @RequestMapping(value = "getBase",method = RequestMethod.GET)
    public Result getBase(){
        List<String> bases = policyAddrMapper.getBaseInfo();
        return Result.success(bases);
    }
    //选择参保地后，获取方案和详情
    @RequestMapping(value = "getCase",method = RequestMethod.GET)
    public Result getCase(@RequestParam String base,@RequestParam int type){
        //type 1 是社保 2是公积金 3是商保
        List<caseDTO> Cases = new ArrayList<>();
        if(type==3){
            List<Map<String,Object>> comminsure = policyAddrMapper.getComminsure();
            System.out.println(comminsure);
            comminsure.forEach(x->{
                caseDTO caseDTO = new caseDTO();
                caseDTO.setProductName(x.get("name").toString());
                caseDTO.setAgeMaxMan(x.get("male_age_max").toString());
                caseDTO.setAgeMaxWoman(x.get("female_age_max").toString());
                caseDTO.setAgeMin(x.get("male_age_min").toString());
                caseDTO.setStartDate(x.get("start_date").toString());
                String cost = policyAddrMapper.getPay(x.get("product_code").toString());
                caseDTO.setTatolCo(cost);
                Cases.add(caseDTO);

            });
        }else {
            List<caseDTO> caseInfo = policyAddrMapper.getCaseInfo(base, type);
            Cases.addAll(caseInfo);
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            Cases.forEach(x->{
                x.getCaseInfoDTOList().forEach(y->{
                    String name = policyAddrMapper.getName(y.getItemTypeCode());
                    y.setItemTypeName(name);
                    Double aDouble = Double.valueOf(decimalFormat.format((float) y.getCompRatio() / 100 * y.getCompBaseMax()));
                    Double aDouble1 = Double.valueOf(decimalFormat.format((float) y.getEmpRatio() / 100 * y.getEmpBaseMax()));
                    Double info = aDouble+aDouble1;
                    y.setCompM(aDouble);
                    y.setEmpM(aDouble1);
                    y.setBN(info);
                });
            });
        }

        return Result.success(Cases);
    }

    //获取续缴详情
    @RequestMapping(value = "getKeepInfo",method = RequestMethod.GET)
    public Result keepPayInfo(@RequestParam String idCard,@RequestParam int type){
        //获取方案名称
        Map<String,String> caseName = policyAddrMapper.getCaseName(idCard, type);
        if(caseName==null){
            return Result.success("没有相关数据");
        }
        //根据方案返回方案详情
        List<caseInfoDTO> info = new ArrayList<>();
        if(type!=3){
            List<caseInfoDTO> caseInfos = policyAddrMapper.getCaseInfos(caseName.get("plan"), type);
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            caseInfos.forEach(x->{
                caseInfoDTO caseInfoDTO = new caseInfoDTO();
                String name = policyAddrMapper.getName(x.getItemTypeCode());
                Double aDouble = Double.valueOf(decimalFormat.format((float) x.getCompRatio() / 100 * Double.parseDouble(caseName.get("cbase"))));
                Double aDouble1 = Double.valueOf(decimalFormat.format((float) x.getEmpRatio() / 100 * Double.parseDouble(caseName.get("cbase"))));
                caseInfoDTO.setItemTypeName(name);
                caseInfoDTO.setBaseEnd(caseName.get("cbase"));
                caseInfoDTO.setEmpM(aDouble1);
                caseInfoDTO.setCompM(aDouble);
                Double infos = aDouble+aDouble1;
                caseInfoDTO.setBN(infos);
                info.add(caseInfoDTO);
            });
        }else {
            caseInfoDTO caseInfoDTO = new caseInfoDTO();
            String comminsures = policyAddrMapper.getComminsures(caseName.get("plan"));
            caseInfoDTO.setItemTypeName(caseName.get("plan"));
            caseInfoDTO.setCompM(Double.parseDouble(comminsures));
            caseInfoDTO.setBN(Double.parseDouble(comminsures));
            info.add(caseInfoDTO);
        }
        return Result.success(info);
    }
    //测试http
    @RequestMapping(value = "getA",method = RequestMethod.GET)
    public Result getA(){
        String url ="https://shebaoapi.renshihr.cn/findYou";
        String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDc1ODMwMTUsInVzZXJpZCI6IjQxMjQxIiwidXNlcm5hbWUiOiLlrrbnlLUiLCJ0b2tlbiI6ImprbGgifQ.f0Pm5RJN2UNbvzfBxQFt0XY18yWrQXFWQ9BWvG-smUc";
        String s = HttpUtil.sendGet(url, token);
        return Result.success(s);
    }

    //获取补缴列表
    @RequestMapping(value = "getBackPay",method = RequestMethod.GET)
    public ResultPage getBackPay(@RequestParam String keyword,@RequestParam String companyId, @RequestParam int page, @RequestParam int size){
       //先把公司下的人查出来
        List<Map<String,String>> idCardList = policyAddrMapper.getPerList(companyId, keyword);
        PageInfo pageInfo = new PageInfo(idCardList);
        Page pageinfos =new Page();
        pageinfos.setPageNum(pageInfo.getPageNum());
        pageinfos.setTotal((int)pageInfo.getTotal());
        List<backPayDTO> backPayDTOList = new ArrayList<>();
        idCardList.forEach(x->{
            backPayDTO backPayDTO = new backPayDTO();
            backPayDTO.setIdCard(x.get("id_card"));
            backPayDTO.setName(x.get("name"));
            BillSociety so = policyAddrMapper.getSo(x.get("id_card"));
            BillAccumulation ac = policyAddrMapper.getAc(x.get("id_card"));
            backPayDTO.setSo(so);
            backPayDTO.setAc(ac);
            backPayDTOList.add(backPayDTO);
        });
        return ResultPage.successp(backPayDTOList,pageinfos);
    }
    //先生成sign
    public static String getSign(CreateOrderDTO createOrderDTO) throws NoSuchAlgorithmException {
        ArrayList<Object> objects = new ArrayList<>();
        objects.add("amount="+createOrderDTO.getAmount()+"&");
        objects.add("auth_code="+createOrderDTO.getAuth_code()+"&");
        objects.add("deduction_amount="+createOrderDTO.getDeduction_amount()+"&");
        objects.add("order_item="+createOrderDTO.getOrder_item()+"&");
        objects.add("order_type="+createOrderDTO.getOrder_type()+"&");
        objects.add("payment_amount="+createOrderDTO.getPayment_amount()+"&");
        objects.add("service_fee="+createOrderDTO.getService_fee()+"&");
        objects.add("shipping_fee="+createOrderDTO.getShipping_fee()+"&");
        objects.add("sign_time="+createOrderDTO.getSign_time()+"&");
        objects.add("userid="+createOrderDTO.getUserid()+"&");
        objects.add(app+appkey);
        String infos= new String();
        // 加密对象，指定加密方式
        for (Object x :objects){
            infos+=x;
        }
        String replace = infos.replace("\\", "");
        byte[] md5s = MessageDigest.getInstance("md5").digest(
                replace.getBytes());
        String md5code = new BigInteger(1, md5s).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;

    }
    //创建订单
    @RequestMapping(value = "createOrder",method = RequestMethod.GET)
    public Result createOrder() throws NoSuchAlgorithmException {
        CreateOrderDTO createOrderDTO = new CreateOrderDTO();
        createOrderDTO.setAmount(101);
        createOrderDTO.setAuth_code("3db06a35534e7b7920a3415cf13ff038");
        createOrderDTO.setDeduction_amount(0);
        String aa="[{\"application_number\":4508590,\"memo\":\"\",\"order_item_detail\":[{\"amount\":1,\"business_amount\":100,\"business_for_year_month\":\"2021-03\",\"identity_number\":\"1\",\"insurance_amount\":100,\"insurance_for_year_month\":\"2021-03\",\"name\":\"1\",\"phone\":\"1\",\"reservefunds_amount\":100,\"reservefunds_for_year_month\":\"2021-03\"}],\"order_item_type\":5,\"person_number\":1,\"price\":100,\"quantity\":1,\"service_price\":20000,\"subtitle\":\"商社保\"}]";
        createOrderDTO.setOrder_item(aa);
        createOrderDTO.setOrder_type(3);
        createOrderDTO.setPayment_amount(101);
        createOrderDTO.setService_fee(0);
        createOrderDTO.setShipping_fee(0);
        BigInteger bigInteger = new BigInteger(String.valueOf(1622516935));
        createOrderDTO.setSign_time(bigInteger);
        createOrderDTO.setUserid(118);
        createOrderDTO.setMemo("");
        createOrderDTO.setAddress("");
        String sign = getSign(createOrderDTO);
        createOrderDTO.setSign(sign);
        //http创建订单
        String s = JSON.toJSONString(createOrderDTO);
        System.out.println(s);
       String info = HttpUtil.sendPost("https://openapi.renshihr.cn/v1/order/add",s,"59551e64bba158de3deb4fc33493fb5a.623893d09cb8c769488238");
        return Result.success(info);
    }
    @Autowired
    private UserServiceIpml userService;
    //创建续签订单
    @RequestMapping(value = "createKeepOrder",method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result createKeepOrder(@RequestBody KeepOrderDTO keepOrderDTOList ) throws NoSuchAlgorithmException {

        String status =null;
        int count =0;

        List<KeepListDTO> keepList = keepOrderDTOList.getKeepList();
        List<KeepBackDTO> keepBackDTOS = new ArrayList<>();
        xuFeiDTO xuFeiDTO = new xuFeiDTO();
        for (KeepListDTO x:keepList) {
            //添加历史记录信息
            RecordAdd recordAdd = new RecordAdd();
            recordAdd.setCompany_name(getCompanyName(x.getUserId()));
            recordAdd.setCompany_id(x.getUserId());
            recordAdd.setName(x.getName());
            recordAdd.setId_card(x.getIdCard());
            if(x.getOrderStatus().contains("1")){
                recordAdd.setService_type(1);
                recordAdd.setHandle_type(4);
                recordAdd.setStatus(1);
                recordAdd.setTtype(4);
                int i2 = userService.setPersonD(recordAdd);
            }
            if(x.getOrderStatus().contains("2")){
                recordAdd.setService_type(2);
                recordAdd.setHandle_type(4);
                recordAdd.setStatus(1);
                recordAdd.setTtype(4);
                int i2 = userService.setPersonD(recordAdd);
            }
            if(x.getOrderStatus().contains("3")){
                recordAdd.setService_type(3);
                recordAdd.setHandle_type(4);
                recordAdd.setStatus(1);
                recordAdd.setTtype(4);
                int i2 = userService.setPersonD(recordAdd);
            }


            String s = policyAddrMapper.checkPson(keepOrderDTOList.getUserId(), x.getIdCard());
            if(s==null){
                return Result.fail("找不到人员信息");
            }
            //获取方案名
            Map<String, String> caseName = policyAddrMapper.getCaseName(x.getIdCard(), 1);
            if(caseName!=null){
                if(!caseName.isEmpty()&&!caseName.get("plan").isEmpty()){
                    x.setPlan(caseName.get("plan"));
                    //查询方案下的险种
                    List<caseInfoDTO> caseInfos = policyAddrMapper.getCaseInfos(caseName.get("plan"), 1);
                    double comPay=0.00;
                    double perPay=0.00;
                    String cbase = policyAddrMapper.getCbase(x.getIdCard(), 1);
                    for ( caseInfoDTO y:caseInfos) {
                        comPay+=y.getCompM()*Integer.parseInt(cbase);
                        perPay+=y.getEmpM()*Integer.parseInt(cbase);
                    }
                    x.setSo_company(comPay);
                    x.setSo_person(perPay);
                }
            }
            Map<String, String> caseName1 = policyAddrMapper.getCaseName(x.getIdCard(), 2);
            if(caseName1!=null){
                if(!caseName1.isEmpty()&&!x.getPlan().isEmpty()&&!caseName1.get("plan").isEmpty()){
                    x.setPlan(x.getPlan()+","+caseName1.get("plan"));
                    //查询方案下的险种
                    List<caseInfoDTO> caseInfos = policyAddrMapper.getCaseInfos(caseName.get("plan"), 2);
                    double comPay=0.00;
                    double perPay=0.00;
                    String cbase = policyAddrMapper.getCbase(x.getIdCard(), 2);
                    for ( caseInfoDTO y:caseInfos) {
                        comPay+=y.getCompM()*Integer.parseInt(cbase);
                        perPay+=y.getEmpM()*Integer.parseInt(cbase);
                    }
                    x.setAc_company(comPay);
                    x.setAc_person(perPay);
                }else {
                    x.setPlan(caseName1.get("plan"));
                }
            }
            Map<String, String> caseName2 = policyAddrMapper.getCaseName(x.getIdCard(), 3);
            if(caseName2!=null){
                if(!caseName2.isEmpty()&&!x.getPlan().isEmpty()&&!caseName2.get("plan").isEmpty()){
                    x.setPlan(x.getPlan()+","+caseName2.get("plan"));
                }else {
                    x.setPlan(caseName1.get("plan"));
                }
            }
            //先生成本地订单

            x.setDateTime(keepOrderDTOList.getKeepDate());
            x.setUserId(keepOrderDTOList.getUserId());
            x.setServiceFee(SERVICECOST);
            x.setOrderStates(x.getOrderStatus());

            //获取token
            String token = getToken();
            //http生成外面的订单
            CreateOrderDTO createOrderDTO = new CreateOrderDTO();
            createOrderDTO.setUserid(Integer.parseInt(keepOrderDTOList.getUserId()));
            createOrderDTO.setOrder_type(3);
            createOrderDTO.setDeduction_amount(0);
            createOrderDTO.setAddress("");
            createOrderDTO.setShipping_fee(SERVICECOST*100);
            createOrderDTO.setAmount((int) Math.round(x.getTotalPay())*100);
            createOrderDTO.setPayment_amount((int) Math.round(x.getTotalPay())*100);
            createOrderDTO.setMemo("");
            createOrderDTO.setAuth_code(AUTHCODE);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            long time = timestamp.getTime();
            createOrderDTO.setSign_time(BigInteger.valueOf(time));
            //订单详情
            CreateOrderInfoDTO createOrderInfoDTO = new CreateOrderInfoDTO();
            createOrderInfoDTO.setApplication_number(6);
            createOrderInfoDTO.setSubtitle("商社保");
            createOrderInfoDTO.setQuantity(1);
            createOrderInfoDTO.setPrice((int) Math.round(x.getTotalPay())*100);
            createOrderInfoDTO.setService_price(SERVICECOST*100);
            createOrderInfoDTO.setPerson_number(1);
            createOrderInfoDTO.setOrder_item_type(5);
            createOrderInfoDTO.setMemo("");

            //订单详情详情
            CreateOrderInfoDetalDTO createOrderInfoDetalDTO = new CreateOrderInfoDetalDTO();
            createOrderInfoDetalDTO.setName(x.getName());
            createOrderInfoDetalDTO.setIdentity_number(x.getIdCard());
            createOrderInfoDetalDTO.setAmount((int) Math.round(x.getTotalPay())*100);
            createOrderInfoDetalDTO.setPhone(s);
            createOrderInfoDetalDTO.setInsurance_for_year_month(keepOrderDTOList.getKeepDate());
            createOrderInfoDetalDTO.setInsurance_amount((int) Math.round(x.getSoPay())*100);
            createOrderInfoDetalDTO.setReservefunds_for_year_month(keepOrderDTOList.getKeepDate());
            createOrderInfoDetalDTO.setReservefunds_amount((int) Math.round(x.getAcPay())*100);
            createOrderInfoDetalDTO.setBusiness_for_year_month(keepOrderDTOList.getKeepDate());
            createOrderInfoDetalDTO.setBusiness_amount((int) Math.round(x.getCoPay())*100);
            ArrayList<CreateOrderInfoDetalDTO> createOrderInfoDetalDTOS = new ArrayList<>();
            createOrderInfoDetalDTOS.add(createOrderInfoDetalDTO);
            createOrderInfoDTO.setOrder_item_detail(createOrderInfoDetalDTOS);
            ArrayList<CreateOrderInfoDTO> createOrderInfoDTOS = new ArrayList<>();
            createOrderInfoDTOS.add(createOrderInfoDTO);
            createOrderDTO.setOrder_item(JSON.toJSONString(createOrderInfoDTOS));
            String sign = getSign(createOrderDTO);
            createOrderDTO.setSign(sign);
            String s1 = JSON.toJSONString(createOrderDTO);
            System.out.println(s1);
            String orderID=null;
            try {
                String info = HttpUtil.sendPost("https://openapi.renshihr.cn/v1/order/add",s1,token);
                System.out.println(info);
                OrderBackDTO jsonObject = JSON.parseObject(info,OrderBackDTO.class);
                if(!"E00000".equals(jsonObject.getStatus_code())){
                    return Result.fail("创建人事云订单失败");
                }
                 orderID = jsonObject.getResult_data().get("order_info").get("order_number");
                System.out.println(orderID);
            }catch (Exception e)
            {e.getMessage();}
            //设置返回值
            KeepBackInfoDTO so = new KeepBackInfoDTO();
            so.setAmount(x.getSoPay()*100);
            so.setFor_year_month(keepOrderDTOList.getKeepDate());
            KeepBackInfoDTO ac = new KeepBackInfoDTO();
            ac.setAmount(x.getAcPay()*100);
            ac.setFor_year_month(keepOrderDTOList.getKeepDate());
            KeepBackInfoDTO co = new KeepBackInfoDTO();
            co.setAmount(x.getCoPay()*100);
            co.setFor_year_month(keepOrderDTOList.getKeepDate());
            KeepBackDTO keepBackDTO = new KeepBackDTO();
            keepBackDTO.setSo(so);
            keepBackDTO.setAc(ac);
            keepBackDTO.setCo(co);
            keepBackDTO.setName(x.getName());
            keepBackDTO.setIdCard(x.getIdCard());
            keepBackDTO.setAmount(x.getTotalPay()*100);
            keepBackDTO.setServicePay(SERVICECOST*100);
            String format = "YYYY-MM-dd";
            String formatDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
            keepBackDTO.setOrderText("续缴订单"+" "+formatDate+"("+"1"+"人"+")");
            keepBackDTO.setOrderId(orderID);
            keepBackDTOS.add(keepBackDTO);
            x.setUuid(orderID);
            x.setOrder_info("续缴");
            try{
                policyAddrMapper.insertOrder(x);
            }catch (Exception e){
                e.getMessage();
            }
            xuFeiDTO.setOrderId(orderID);
            xuFeiDTO.setOrderText("续缴订单"+" "+formatDate+"("+keepList.size()+"人"+")");
        }
        xuFeiDTO.setData(keepBackDTOS);
        return Result.success(xuFeiDTO);
    }
    //支付签名
    public static String getPaySign(PayKeepOrderDTO payKeepOrderDTO) throws NoSuchAlgorithmException {
        ArrayList<Object> objects = new ArrayList<>();
        objects.add("amount="+payKeepOrderDTO.getAmount()+"&");
        objects.add("auth_code="+payKeepOrderDTO.getAuth_code()+"&");
        objects.add("notice_url="+payKeepOrderDTO.getNotice_url()+"&");
        objects.add("order_number="+payKeepOrderDTO.getOrder_number()+"&");
        objects.add("payment_type="+payKeepOrderDTO.getPayment_type()+"&");
        objects.add("sign_time="+payKeepOrderDTO.getSign_time()+"&");
        objects.add("userid="+payKeepOrderDTO.getUserid()+"&");
        objects.add(app+appkey);
        String infos= new String();
        // 加密对象，指定加密方式
        for (Object x :objects){
            infos+=x;
        }
        String replace = infos.replace("\\", "");
        System.out.println(replace);
        byte[] md5s = MessageDigest.getInstance("md5").digest(
                replace.getBytes());
        String md5code = new BigInteger(1, md5s).toString(16);
        for (int i = 0; i < 32 - md5code.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;

    }
    //支付续签/补缴订单
    @RequestMapping(value = "payKeepOrder",method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result payKeepOrder(@RequestBody List<PayKeepOrderDTO> payKeepOrderDTO) throws NoSuchAlgorithmException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        long time = timestamp.getTime();
        //获取token
        String token = getToken();
        for (PayKeepOrderDTO x:payKeepOrderDTO) {
            x.setNotice_url("https://shebaoapi.renshihr.cn/shangshebao/payKeepOrderBack");
            x.setAuth_code(AUTHCODE);
            x.setSign_time(String.valueOf(time));
            String paySign = getPaySign(x);
            System.out.println(paySign);
            x.setSign(paySign);
            try {
                String s1 = JSON.toJSONString(x);
                System.out.println(s1);
                System.out.println(token);
                String s = HttpUtil.sendPost("https://openapi.renshihr.cn/v1/order/pay", s1, token);
                System.out.println(s);
                OrderBackDTO jsonObject = JSON.parseObject(s,OrderBackDTO.class);
                if(!"E00000".equals(jsonObject.getStatus_code())){
                    return Result.fail("人事云订单支付失败");
                }
            }catch (Exception e){
                e.getMessage();
            }
        }
        return Result.success("操作成功");
    }
    //支付回调地址
    @RequestMapping(value = "payKeepOrderBack",method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String payKeepOrderBack(@RequestBody PayKeepBackDTO payKeepBackDTO) throws ParseException {
        //查询订单修改订单状
        int i = policyAddrMapper.updataOrder(payKeepBackDTO.getOrder_number());
        Order order = policyAddrMapper.foundOrder(payKeepBackDTO.getOrder_number());
        if("增员".equals(order.getOrder_info())){
            String substring = payKeepBackDTO.getPayment_date().substring(0, 4);
            String substring1 = payKeepBackDTO.getPayment_date().substring(5, 7);
            Calendar cal= Calendar.getInstance();
            cal.set(Calendar.YEAR, Integer.parseInt(substring));
            cal.set(Calendar.MONTH, Integer.parseInt(substring1)-1);
            cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
            String Stime = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
            Calendar cal1= Calendar.getInstance();
            cal1.set(Calendar.YEAR, Integer.parseInt(substring));
            cal1.set(Calendar.MONTH, Integer.parseInt(substring1)-1);
            cal1.set(Calendar.DAY_OF_MONTH, cal1.getActualMaximum(Calendar.DATE));
            String Etime =new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime());
            if(order.getOrder_states().contains("1")){
                policyAddrMapper.getUpAdd(order.getId_card(),1,Stime,Etime);
            }
            if(order.getOrder_states().contains("2")){
                policyAddrMapper.getUpAdd(order.getId_card(),2,Stime,Etime);
            }
            if(order.getOrder_states().contains("3")){
                policyAddrMapper.getUpAdd(order.getId_card(),3,Stime,Etime);
            }
        }
        if("续缴".equals(order.getOrder_info())){
            //查社保情况
            if(order.getOrder_states().contains("1")){
                BillSociety so = policyAddrMapper.getSo(order.getId_card());
                LocalDate keep_end_time = so.getKeep_end_time();
                String substring = payKeepBackDTO.getPayment_date().substring(0, 4);
                String substring1 = payKeepBackDTO.getPayment_date().substring(5, 7);
                Calendar cal= Calendar.getInstance();
                cal.set(Calendar.YEAR, Integer.parseInt(substring));
                cal.set(Calendar.MONTH, Integer.parseInt(substring1)-1);
                cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
                String Stime = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
                Calendar cal1= Calendar.getInstance();
                cal1.set(Calendar.YEAR, Integer.parseInt(substring));
                cal1.set(Calendar.MONTH, Integer.parseInt(substring1)-1);
                cal1.set(Calendar.DAY_OF_MONTH, cal1.getActualMaximum(Calendar.DATE));
                String Etime =new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime());
                if(keep_end_time.isAfter(LocalDate.now())){
                    //修改结束时间
                    policyAddrMapper.updataOrderE(order.getId_card(), Etime);
                }else {
                    //修改开始时间和结束时间
                    policyAddrMapper.updataOrderS(order.getId_card(),Stime, Etime);
                }
            }
            //查公积金情况
            if(order.getOrder_states().contains("2")){
                BillAccumulation ac = policyAddrMapper.getAc(order.getId_card());
                LocalDate keep_end_time = ac.getKeep_end_time();
                String substring = payKeepBackDTO.getPayment_date().substring(0, 4);
                String substring1 = payKeepBackDTO.getPayment_date().substring(5, 7);
                Calendar cal= Calendar.getInstance();
                cal.set(Calendar.YEAR, Integer.parseInt(substring));
                cal.set(Calendar.MONTH, Integer.parseInt(substring1)-1);
                cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
                String Stime = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
                Calendar cal1= Calendar.getInstance();
                cal1.set(Calendar.YEAR, Integer.parseInt(substring));
                cal1.set(Calendar.MONTH, Integer.parseInt(substring1)-1);
                cal1.set(Calendar.DAY_OF_MONTH, cal1.getActualMaximum(Calendar.DATE));
                String Etime =new SimpleDateFormat("yyyy-MM-dd").format(cal1.getTime());
                if(keep_end_time.isAfter(LocalDate.now())){
                    //修改结束时间
                    policyAddrMapper.updataOrderEE(order.getId_card(), Etime);

                }else {
                    //修改开始时间和结束时间
                    policyAddrMapper.updataOrderSS(order.getId_card(),Stime, Etime);
                }
            }
        }
        return "{"+"\"return_code\": \"success\"" + "}";
    }

    //获取token方法
    public String getToken(){
        //获取token
        tokenDTO tokenDTO = new tokenDTO();
        tokenDTO.setChecked(1);
        tokenDTO.setPassword("a123456");
        tokenDTO.setLogin_type("enterprise");
        tokenDTO.setUsername("weilai");
        tokenDTO.setReferer_url("http://archive.renshihr.com");
        String token = JSON.toJSONString(tokenDTO);
        String substring = null;
        try{
            String s3 = HttpUtil.sendPost1("https://tpa.renshihr.cn/api/user/login?referer_url=archive.reshihr.cn", token, null);
            tokenInfoDTO jsonObject = JSON.parseObject(s3,tokenInfoDTO.class);
            Map<String, Object> obj = jsonObject.getObj();
            String referer_url = obj.get("referer_url").toString();
            int i = referer_url.indexOf("=");
            int a = referer_url.indexOf("&");
            substring = referer_url.substring(i+1, a);
        }catch (Exception e){e.getMessage();}
        return substring;
    }
    @Autowired
    private JobUtil jobUtil;
    //定时任务测试
    @RequestMapping(value = "getB",method = RequestMethod.GET)
    public Result getB(){
        jobUtil.upDataRepair();
        return Result.success(null);
    }
    //获取第一次时间
    @RequestMapping(value = "getFristDate",method = RequestMethod.GET)
    public Result getTime1 (@RequestParam String companyId){
        System.out.println(111);
        String ft = billMapper.getFT(companyId);
        if(ft==null){
            return Result.fail("该企业未执行添加员工操作");
        }
        //获取单独年月
        Long fristYear=Long.parseLong(ft.substring(0,4));
        Long fristMonth=Long.parseLong(ft.substring(5,7));
        Calendar date = Calendar.getInstance();
        Long nowYear = Long.parseLong(String.valueOf(date.get(Calendar.YEAR)));
        Long nowMonth = Long.parseLong(String.valueOf(date.get(Calendar.MONTH)+1));
        timeDTO timeDTO = new timeDTO();
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        ArrayList<com.zhengxin.one.dto.timeDTO> timeDTOS = new ArrayList<>();
        int i;
        int m=1;
        long l = (nowYear - fristYear) * 12 + (nowMonth - fristMonth);
        for(i=Integer.parseInt(String.valueOf(l)); i>0; i--){
            com.zhengxin.one.dto.timeDTO timeDTO1 = new timeDTO();
            Date dd = new Date();
            Calendar calendar = Calendar.getInstance(); //创建Calendar 的实例
            calendar.setTime(dd);
            calendar.add(Calendar.MONTH, -m);//当前时间减去一个月，即一个月前的时间
            Date dt1=calendar.getTime();
            String reStr = sdf.format(dt1);
            calendar.add(Calendar.MONTH, -1);//当前时间减去一个月，即一个月前的时间
            Date dt2=calendar.getTime();
            String reStr1 = sdf.format(dt2);
            timeDTO1.setDate(reStr1+"-01 00:00:00");
            timeDTO1.setMonth(reStr);
            timeDTOS.add(timeDTO1);
            m++;
            }
        return Result.success(timeDTOS);
    }

    //首页商保理赔中
    @RequestMapping(value = "getCP",method = RequestMethod.GET)
    public Result getCP (@RequestParam String companyId){
        int cPs = policyAddrMapper.getCPs(companyId);
        return Result.success(cPs);
    }
    @RequestMapping(value = "getSP",method = RequestMethod.GET)
    public Result getSP (@RequestParam String companyId){
        int cPs = policyAddrMapper.getSPs(companyId);
        return Result.success(cPs);
    }
    //首页商保理赔中
    @RequestMapping(value = "getSE",method = RequestMethod.GET)
    public Result getSE (@RequestParam String companyId){
        List<Map> sEs = policyAddrMapper.getSEs(companyId);
        return Result.success(sEs);
    }
    //首页商保理赔中
    @RequestMapping(value = "getAE",method = RequestMethod.GET)
    public Result getAE (@RequestParam String companyId){
        List<Map> sEs = policyAddrMapper.getAEs(companyId);
        return Result.success(sEs);
    }
    //首页商保理赔中
    @RequestMapping(value = "getCE",method = RequestMethod.GET)
    public Result getCE (@RequestParam String companyId){
        List<Map> sEs = policyAddrMapper.getCEs(companyId);
        return Result.success(sEs);
    }

    //首页获取余额
    @RequestMapping(value = "getCompanyInfo",method = RequestMethod.GET)
    public Result getCompanyInfo (@RequestParam String companyId){
        String s3 = HttpUtil.sendGet("https://openapi.renshihr.cn/v1/user/account/info?userid="+companyId, getToken());
        if(s3.isEmpty()){
            return Result.fail("获取失败");
        }
        return Result.success( JSONUtil.parseObj(JSONUtil.parseObj(s3).get("result_data").toString()).get("freeze_balance"));
    }

    //首页待支付订单数量
    @RequestMapping(value = "getOrderCount",method = RequestMethod.GET)
    public Result getOrderCount (@RequestParam String companyId){
        int orderD = policyAddrMapper.getOrderD(companyId);
        return Result.success(orderD);
    }

    //首页调公司信息接口
    @RequestMapping(value = "getCompany",method = RequestMethod.GET)
    public Result getCompany (@RequestParam String token){
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("token",token);
        String token1 = JSON.toJSONString(stringStringHashMap);
        String s = HttpUtil.sendPost1("https://tpa.renshihr.cn/api/v1/company_manage/info/get",token1, null);
        return Result.success(JSONUtil.parseObj(s));
    }
    //首页调公司信息接口
    @RequestMapping(value = "getPerson",method = RequestMethod.GET)
    public Result getPerson (@RequestParam String token){
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("token",token);
        String token1 = JSON.toJSONString(stringStringHashMap);
        String s = HttpUtil.sendPost1("https://tpa.renshihr.cn/api/v1/person_manage/info/get",token1, null);
        return Result.success(JSONUtil.parseObj(s));
    }
    //首页调公司信息接口
    @RequestMapping(value = "getUser",method = RequestMethod.GET)
    public Result getUser (@RequestParam String token){
        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("token",token);
        String token1 = JSON.toJSONString(stringStringHashMap);
        String s = HttpUtil.sendPost1("https://tpa.renshihr.cn/api/user/info",token1, null);
        return Result.success(JSONUtil.parseObj(s));
    }
}
